<template>
  <div>
    <div class="top">
      <div class="card">
        <div class="card-item">
          <div>
            收入<span>{{ allData.totalIncome }}</span>元
          </div>
        </div>
        <div class="card-item">
          <div>
            支出<span>{{ allData.totalExpend }}</span>元
          </div>
        </div>
        <div class="card-item">
          <div>
            余额<span>{{ allData.totalRemain }}</span>元
          </div>
        </div>
        <el-button @click="saveReport"
          style="background-color:azure;border-radius: 50%;margin-left: 30px;">保存报表</el-button>
      </div>
      <div class="top-options">
        <el-select style="width: 290px; margin-right: 20px" v-model="userId" placeholder="请选择家庭成员"
          @change="changeUserId">
          <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-radio-group v-model="timeType" @change="changeTime">
          <el-radio-button label="1">本月</el-radio-button>
          <el-radio-button label="2">近三月</el-radio-button>
          <el-radio-button label="3">近半年</el-radio-button>
          <el-radio-button label="4">近一年</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <div class="chart-container">
      <div id="radarChart" class="chart-item1"></div>
      <div id="pieChart" class="chart-item2"></div>
      <div id="barChart" class="chart-item4"></div>
      <div id="lineChart" class="chart-item3"></div>

    </div>
  </div>
</template>

<script>
import { get } from '../../utils/http'
import html2canvas from 'html2canvas'
import * as echarts from 'echarts';

export default {
  name: 'Statsitics',
  mounted() {
    this.$echarts = echarts;
    this.getUser();
    this.$nextTick(() => {
      this.changeTime();
      this.getPieData();
      this.drawRadar();
      this.drawBar();
    });
  },
  data() {
    return {
      timeType: '1',
      allData: {},
      lineData: {},
      pieData: [],
      userList: [],
      userId: '000000',
      onlySelf: false,
      radarData: [],
      barData: [],
    }
  },
  methods: {
    drawLine() {
      let myChart = this.$echarts.init(document.getElementById('lineChart'))
      myChart.setOption({
        title: {
          text: '收入支出统计',
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: ['收入', '支出'],
        },
        color: ['#228B22', '#8B0000'],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.lineData.dateList ? this.lineData.dateList : [],
          axisLine: {
            show: false,
          },
        },
        yAxis: {
          type: 'value',
          splitLine: {
            lineStyle: {
              type: 'dashed',
            },
          },
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
        },
        series: [
          {
            name: '收入',
            type: 'line',
            stack: '总量',
            data: this.lineData.incomeList ? this.lineData.incomeList : [],
          },
          {
            name: '支出',
            type: 'line',
            stack: '总量',
            data: this.lineData.expendList ? this.lineData.expendList : [],
          },
        ],
      })
    },
    drawPie() {
      get('/bill/statisticsType', {
        houseId: sessionStorage.getItem('houseId'),
        userId: this.userId === '000000' ? sessionStorage.getItem('userId') : this.userId,
        timeType: this.timeType,
        onlySelf: this.onlySelf,
      }).then((res) => {
        if (res.description === 'success') {
          this.pieData = res.data.map(item => ({ name: item.name, value: item.money }));
          let myChart = this.$echarts.init(document.getElementById('pieChart'))
          myChart.setOption({
            title: {
              text: '消费类型-饼图',
            },
            tooltip: {
              trigger: 'item',
            },
            legend: {
              data: this.pieData.map((item) => item.name),
            },
            color: [
              '#85c7de',
              '#e7d8c9',
              '#CDB4DB',
              '#c9f2c7',
              '#FFC8DD',
            ],
            series: [
              {
                name: '消费类型',
                type: 'pie',
                radius: '65%',
                center: ['50%', '55%'],
                avoidLabelOverlap: false,
                itemStyle: {
                  borderRadius: 10,
                  borderColor: '#fff',
                  borderWidth: 2,
                },
                label: {
                  show: false,
                  position: 'center',
                },
                labelLine: {
                  show: false,
                },
                data: this.pieData,
              },
            ],
          })
        }
      })
    },
    drawRadar() {
      get('/bill/statisticsType', {
        houseId: sessionStorage.getItem('houseId'),
        userId: this.userId === '000000' ? sessionStorage.getItem('userId') : this.userId,
        timeType: this.timeType,
        onlySelf: this.onlySelf,
      }).then((res) => {
        if (res.description === 'success') {
          this.radarData = res.data.map(item => ({
            name: item.name,
            max: Math.max(...res.data.map(i => i.money)),
            value: item.money
          }));
          let myChart = this.$echarts.init(document.getElementById('radarChart'))
          myChart.setOption({
            title: {
              text: '消费类型-雷达图',
            },
            tooltip: {},
            radar: {
              indicator: this.radarData.map(item => ({ name: item.name, max: item.max })),
              splitArea: {
                areaStyle: {
                  color: ['#f0f8ff', '#e6f7ff'],
                }
              },
              axisLabel: {
                color: '#00008B',
                fontSize: 14
              }
            },
            series: [{
              name: '消费类型',
              type: 'radar',
              data: [
                {
                  value: this.radarData.map(item => item.value),
                  name: '消费类型'
                }
              ],
              itemStyle: {
                color: '#00BFFF'
              }
            }]
          })
        }
      })
    },
    drawBar() {
      get('/bill/statisticsType', {
        houseId: sessionStorage.getItem('houseId'),
        userId: this.userId === '000000' ? sessionStorage.getItem('userId') : this.userId,
        timeType: this.timeType,
        onlySelf: this.onlySelf,
      }).then((res) => {
        if (res.description === 'success') {
          this.barData = res.data.map(item => ({
            name: item.name,
            value: item.money
          }));
          let myChart = this.$echarts.init(document.getElementById('barChart'))
          myChart.setOption({
            title: {
              text: '消费类型-柱状图',
            },
            tooltip: {},
            grid: {
              top: '30%',
              left: '10%',
              right: '10%',
              bottom: '10%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              data: this.barData.map(item => item.name),
            },
            yAxis: {
              type: 'value',
            },
            series: [{
              data: this.barData.map(item => item.value),
              type: 'bar',
              itemStyle: {
                color: (params) => {
                  const colors = ['#85c7de', '#e7d8c9', '#CDB4DB', '#c9f2c7', '#FFC8DD'];
                  return colors[params.dataIndex % colors.length];
                }
              }
            }]
          })
        }
      })
    },
    getData() {
      get('/bill/statisticsByTime', {
        houseId: sessionStorage.getItem('houseId'),
        userId:
          this.userId === '000000'
            ? sessionStorage.getItem('userId')
            : this.userId,
        timeType: this.timeType,
        onlySelf: this.onlySelf,
      }).then((res) => {
        if (res.description === 'success') {
          this.allData = {
            totalIncome: res.data.totalIncome,
            totalExpend: res.data.totalExpend,
            totalBudget: res.data.totalBudget,
            totalRemain: (res.data.totalIncome - res.data.totalExpend).toFixed(
              2
            ),
          }
          console.log(this.allData.totalIncome)
          this.drawPie()
        }
      })
    },
    getLineData() {
      get('/bill/statisticsLineChart', {
        houseId: sessionStorage.getItem('houseId'),
        userId:
          this.userId === '000000'
            ? sessionStorage.getItem('userId')
            : this.userId,
        timeType: this.timeType,
        onlySelf: this.onlySelf,
      }).then((res) => {
        if (res.description === 'success') {
          Object.assign(this.lineData, res.data)
          this.drawLine()
        }
      })
    },
    getPieData() {
      get('/bill/statisticsType', {
        houseId: sessionStorage.getItem('houseId'),
        userId:
          this.userId === '000000'
            ? sessionStorage.getItem('userId')
            : this.userId,
        timeType: this.timeType,
        onlySelf: this.onlySelf,
      }).then((res) => {
        if (res.description === 'success') {
          if (res.data.length) {
            let newData = []
            res.data.forEach((element) => {
              newData.push({ name: element.name, value: element.money })
            })
            this.pieData = newData
            this.drawPie()
            this.drawRadar()
            this.drawBar()
          }
        }
      })
    },
    changeTime() {
      this.getData()
      this.getLineData()
      this.getPieData()
    },
    getUser() {
      get('/user/query', {
        houseId: sessionStorage.getItem('houseId'),
      }).then((res) => {
        if (res.description === 'success') {
          this.userList = res.data.list
          this.userList.unshift({
            id: '000000',
            name: '全部',
          })
        }
      })
    },
    changeUserId(userId) {
      this.onlySelf = false
      if (userId === Number(sessionStorage.getItem('userId'))) {
        this.onlySelf = true
      }
      this.userId = userId
      this.changeTime()
    },
    saveReport() {
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
      const fileName = `data-report-${timestamp}.png`;
      html2canvas(document.querySelector(".chart-container")).then(canvas => {
        const link = document.createElement('a');
        link.download = `C:\\Users\\${process.env.USERNAME}\\Desktop\\${fileName}`;
        link.href = canvas.toDataURL();
        link.click();
      });
    }
  },
}
</script>

<style>
.top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: -30px;
}

.top-options {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  margin-top: -20px;
}

.card {
  display: flex;
  padding-bottom: 20px;
}

.card-item {
  display: flex;
  flex-direction: column;
  padding: 10px 20px;
  border: 1px solid #27cff0;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  border-radius: 50px;
  margin-right: 10px;
}

.card-item:nth-child(1) span {
  padding: 0 5px;
  color: #67c23a;
}

.card-item:nth-child(2) span {
  color: #e6a23c;
  padding: 0 5px;
}

.card-item:nth-child(3) span {
  color: #f56c6c;
  padding: 0 5px;
}

.chart-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.chart-item1 {
  width: calc(50% - 20px);
  height: 300px;
  margin-bottom: 20px;
}

.chart-item2 {
  width: calc(50% - 20px);
  height: 300px;
  margin-bottom: 20px;
}

.chart-item3 {
  width: calc(50% - 20px);
  height: 280px;
  margin-bottom: 20px;
  margin-top: -20px;
}

.chart-item4 {
  width: calc(50% - 20px);
  height: 280px;
  margin-bottom: 20px;
  margin-top: -20px;
}
</style>
